// pages/map/map.js
var QQMapWX = require('../../libs/qqmap-wx-jssdk.js');
var qqmapsdk;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    latitude: 30.872743,
    longitude: 120.128639,
    subKey: 'FFNBZ-PXPCX-HRA4E-7EQXT-RUVAT-UEFKW',
    enable3d: false,
    showLocation: true,
    showCompass: false,
    enableOverlooking: false,
    enableZoom: true,
    enableScroll: true,
    enableRotate: false,
    drawPolygon: false,
    enableSatellite: false,
    enableTraffic: false,
    latitude: '30.873496',
    longitude: '120.131063',
    markers: [],
    callouts: [],
    callout: {},
    showDialog: false,
    currentMarker: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    qqmapsdk = new QQMapWX({
      key: 'FFNBZ-PXPCX-HRA4E-7EQXT-RUVAT-UEFKW'
    });
     /* wx.startLocationUpdate({
       success: () => {
        wx.onLocationChange((result) => {
          this.setData({
            latitude: result.latitude,
            longitude: result.longitude,
            markers: [{
              latitude: result.latitude,
              longitude: result.longitude
            }]
          })
        })
       }
     }) */
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    const map = wx.createMapContext("map");
    map.moveToLocation();
    wx.request({
      url: 'https://car.ispongecity.com/lesson/features/layer/充电',
      success: (result) => {
        console.log(result.data);
        const callouts = result.data.map((item,index) => {
          return {
            id: index
          };
        });
        const array = result.data.filter(item => item.properties["名称"].indexOf("西") != -1);
        const markers = result.data.map((item,index) => {
          return {
            id: index,
            latitude: item.geometry.coordinates[1],
            longitude: item.geometry.coordinates[0],
            properties: item.properties,
            width: 16,
            height: 16,
            iconPath: '../../images/map_charge.png',
            label: {
              content: item.properties['名称']
            },
            callout: {
              content: item.properties['名称']
            },
            customCallout: {

            }
          }
        });
        this.setData({
          markers: markers,
          callouts: callouts
        });
      }
    })
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    //wx.stopLocationUpdate();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  handleTap(e) {
    console.log(e);
  },

  handleMarkerTap(e) {
    console.log(e);
    const marker = this.data.markers.find(item => item.id == e.markerId);
    marker && this.setData({
      currentMarker: marker,
      showDialog: true
    });
  },

  navi1() {
    const latitude = this.data.currentMarker.latitude;
    const longitude = this.data.currentMarker.longitude;
    wx.openLocation({
      latitude,
      longitude,
      scale: 18
    });
  },

  navi2() {
    wx.getLocation({
      type: 'gcj02', //返回可以用于wx.openLocation的经纬度
      success: (res) => {
        const latitude = res.latitude
        const longitude = res.longitude
        qqmapsdk.direction({
          mode: 'driving',//可选值：'driving'（驾车）、'walking'（步行）、'bicycling'（骑行），不填默认：'driving',可不填
          //from参数不填默认当前地址
          from: {
            latitude: latitude,
            longitude: longitude
          },
          to: {
            latitude: this.data.currentMarker.latitude,
            longitude: this.data.currentMarker.longitude
          }, 
          success:  (res) => {
            console.log(res);
            var ret = res;
            var coors = ret.result.routes[0].polyline, pl = [];
            //坐标解压（返回的点串坐标，通过前向差分进行压缩）
            var kr = 1000000;
            for (var i = 2; i < coors.length; i++) {
              coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr;
            }
            //将解压后的坐标放入点串数组pl中
            for (var i = 0; i < coors.length; i += 2) {
              pl.push({ latitude: coors[i], longitude: coors[i + 1] })
            }
            console.log(pl)
            //设置polyline属性，将路线显示出来,将解压坐标第一个数据作为起点
            this.setData({
              latitude:pl[0].latitude,
              longitude:pl[0].longitude,
              polyline: [{
                points: pl,
                arrowLine: true,
                color: '#1aad19dd',           
                width: 4,
                borderColor: '#1aad19FF',
                borderWidth: 1
              }],
              showDialog: false
            })
          },
          fail: function (error) {
            console.error(error);
          },
          complete: function (res) {
            console.log(res);
          }
        });
      }
    });
    
  }
})